<template>
  <div class="ledger-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>设备管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Menu /></el-icon>
          <span>设备台账</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="filter-form" @keyup.enter="handleSearch">
        <el-form-item>
          <el-input v-model="searchForm.devicenameorcode" placeholder="请输入设备编号或名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-tree-select
            v-model="searchForm.device_typetreeid"
            :data="deviceTypeTreeOptions"
            :props="treeSelectProps"
            check-strictly
            placeholder="请选择设备类型"
            clearable
            class="w-220"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.workshopid" placeholder="请选择所属车间" clearable class="w-180">
            <el-option v-for="opt in workshopOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" @click="openCreateDialog">新增</el-button>
        <el-button>导入</el-button>
        <el-button>导出</el-button>
      </div>

      <el-table :data="pagedRows" border stripe :loading="loading" class="ledger-table" height="680">
        <el-table-column type="selection" width="48" />
        <el-table-column label="序号" type="index" width="64" />
        <el-table-column prop="devicename" label="设备名称" min-width="140" />
        <el-table-column prop="devicecode" label="设备编号" min-width="140" />
        <el-table-column prop="devicemodel" label="规格型号" min-width="120" />
        <el-table-column prop="brand" label="品牌" min-width="100" />
        <el-table-column prop="workshopname" label="所属车间" min-width="120" />
        <el-table-column prop="device_typetree" label="设备分类" min-width="140" />
        <el-table-column label="设备状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'info'">{{ scope.row.status ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bz" label="备注" min-width="160" show-overflow-tooltip />
        <el-table-column prop="creator" label="创建人" min-width="100" />
        <el-table-column prop="createtime" label="创建时间" min-width="170">
          <template #default="scope">{{ formatTime(scope.row.createtime) }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-link type="primary" @click="openEditDialog(scope.row)">编辑</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" @click="handleDelete(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="rows.length"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.mode === 'create' ? '新增设备' : '编辑设备'" width="640px" @closed="onDialogClosed">
      <el-form :model="form" :rules="dialogRules" ref="formRef" label-width="96px">
        <el-form-item label="设备编号" prop="devicecode">
          <div class="flex-row gap-8 w-100">
            <el-input v-model="form.devicecode" placeholder="请输入" />
            <el-switch v-model="form.autoCode" @change="onAutoCodeToggle" />
          </div>
        </el-form-item>
        <el-form-item label="设备名称" prop="devicename">
          <el-input v-model="form.devicename" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="规格型号" prop="devicemodel">
          <el-input v-model="form.devicemodel" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="所属车间" prop="workshopid">
          <el-select v-model="form.workshopid" placeholder="请选择所属车间" clearable>
            <el-option v-for="opt in workshopOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="device_typetreeid">
          <el-tree-select
            v-model="form.device_typetreeid"
            :data="deviceTypeTreeOptions"
            :props="treeSelectProps"
            check-strictly
            placeholder="设备类型"
            filterable
            class="w-100"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item>
        <el-form-item label="备注" prop="bz">
          <el-input v-model="form.bz" type="textarea" :rows="3" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import https from '@/Http/http'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { ArrowRight, HomeFilled, Setting, Menu } from '@element-plus/icons-vue'

interface LedgerItem {
  id?: number
  devicecode: string
  devicename: string
  devicemodel: string
  brand: string
  workshopid: number
  device_typetreeid: number
  status: boolean
  bz: string
  creator: string
  createtime: string | Date
  workshopname: string
  device_typetree: string
}

// 使用统一的https.Reads路由

const loading = ref(false)
const rows = ref<LedgerItem[]>([])

const pager = reactive({ page: 1, size: 10 })
const pagedRows = computed(() => {
  const start = (pager.page - 1) * pager.size
  return rows.value.slice(start, start + pager.size)
})

const treeSelectProps = { label: 'label', children: 'children', value: 'value' }
const deviceTypeTreeOptions = ref<any[]>([])

const workshopOptions = ref<{label:string; value:number}[]>([])

const searchForm = reactive({ devicenameorcode: '', device_typetreeid: undefined as number | undefined, workshopid: undefined as number | undefined })

const formRef = ref<FormInstance>()
const dialog = reactive({ visible: false, mode: 'create' as 'create' | 'edit' })
const form = reactive({
  id: undefined as number | undefined,
  devicecode: '',
  devicename: '',
  devicemodel: '',
  brand: '',
  workshopid: undefined as number | undefined,
  device_typetreeid: undefined as number | undefined,
  status: true,
  bz: '',
  autoCode: false,
})

const dialogRules = reactive<FormRules>({
  devicecode: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  devicename: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  device_typetreeid: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  workshopid: [{ required: true, message: '请选择所属车间', trigger: 'change' }],
})

const formatTime = (val: any) => {
  if (!val) return ''
  const d = new Date(val)
  const pad = (n: number) => `${n}`.padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

const buildTreeOptions = (list: any[]): any[] => {
  // 后端已返回 { value, label, children } 的树形结构，直接使用
  return Array.isArray(list) ? list : []
}

const fetchDeviceTypeTree = async () => {
  const { data } = await https.Reads.get('/ADeviceManagement/Showdevice_typetreeModel')
  const arr = data?.data ?? []
  deviceTypeTreeOptions.value = buildTreeOptions(arr)
}

const fetchWorkshops = async () => {
  try {
    const { data } = await https.Reads.get('/ADeviceManagement/AAWorkshopShow')
    const list = Array.isArray(data?.data) ? data.data : []
    workshopOptions.value = list.map((w: any) => ({ label: w.workshopname, value: w.id }))
  } catch (e) {
    workshopOptions.value = []
  }
}

const fetchList = async () => {
  loading.value = true
  try {
    const { data } = await https.Reads.get('/ADeviceManagement/AEquipment_LedgerShow', { params: {
      devicenameorcode: searchForm.devicenameorcode || undefined,
      device_typetreeid: searchForm.device_typetreeid || 0,
      workshopid: searchForm.workshopid || 0,
    } })
    rows.value = data?.data ?? []
    pager.page = 1
  } finally {
    loading.value = false
  }
}

const handleSearch = () => { fetchList() }
const handleReset = () => {
  searchForm.devicenameorcode = ''
  searchForm.device_typetreeid = undefined
  searchForm.workshopid = undefined
  fetchList()
}

const resetForm = () => {
  form.id = undefined
  form.devicecode = ''
  form.devicename = ''
  form.devicemodel = ''
  form.brand = ''
  form.workshopid = undefined
  form.device_typetreeid = undefined
  form.status = true
  form.bz = ''
  form.autoCode = false
  formRef.value?.clearValidate()
}

const openCreateDialog = () => { dialog.mode = 'create'; resetForm(); dialog.visible = true }
const openEditDialog = (row: LedgerItem) => {
  dialog.mode = 'edit'
  form.id = undefined
  form.devicecode = row.devicecode
  form.devicename = row.devicename
  form.devicemodel = row.devicemodel
  form.brand = row.brand
  form.workshopid = row.workshopid
  form.device_typetreeid = row.device_typetreeid
  form.status = !!row.status
  form.bz = row.bz
  form.autoCode = false
  dialog.visible = true
}

const onDialogClosed = () => { resetForm() }

const genCode = () => {
  const now = new Date()
  const p = (n: number) => `${n}`.padStart(2, '0')
  return `SBBH${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`
}
const onAutoCodeToggle = () => { if (form.autoCode) form.devicecode = genCode() }

const submitLoading = ref(false)
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload: any = {
        devicecode: form.devicecode,
        devicename: form.devicename,
        devicemodel: form.devicemodel,
        brand: form.brand,
        workshopid: form.workshopid,
        device_typetreeid: form.device_typetreeid,
        status: form.status,
        bz: form.bz,
      }
      let res
      if (dialog.mode === 'create') {
        res = await https.Writes.post('/AEquipment/DeviceMessageAdd', payload)
      } else {
        payload.id = form.id
        res = await https.Writes.post('/AEquipment/DeviceMessageEdit', payload)
      }
      if (res.data && res.data.code === 200) {
        ElMessage.success(dialog.mode === 'create' ? '新增成功' : '编辑成功')
        dialog.visible = false
        await fetchList()
      } else {
        ElMessage.error(res.data?.msg || '保存失败')
      }
    } catch (e: any) {
      ElMessage.error(e?.message || '保存失败')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleDelete = (row: LedgerItem) => {
  ElMessageBox.confirm(`确认删除「${row.devicename}」吗？`, '提示', { type: 'warning' })
    .then(async () => {
      try {
        const res = await https.Writes.post('/AEquipment/DeviceMessageDelete', { id: (row as any).id })
        if (res.data && res.data.code === 200) {
          ElMessage.success('删除成功')
          await fetchList()
        } else {
          ElMessage.error(res.data?.msg || '删除失败')
        }
      } catch (e: any) {
        ElMessage.error(e?.message || '删除失败')
      }
    })
    .catch(() => {})
}

onMounted(async () => {
  await fetchDeviceTypeTree()
  await fetchWorkshops()
  await fetchList()
})
</script>

<style scoped>
.ledger-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  position: relative;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-image:
    url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5z' fill='%23ffffff' fill-opacity='0.03' fill-rule='evenodd'/%3E%3C/svg%3E"),
    linear-gradient(135deg, #667eea15 0%, #764ba215 50%, #f093fb15 100%);
  background-size: 200px 200px, cover;
  background-position: 0 0, center;
  background-attachment: fixed;
}

.ledger-page::before {
  content: "";
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background:
    radial-gradient(circle at 20% 50%, rgba(102, 126, 234, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 80% 80%, rgba(118, 75, 162, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 40% 20%, rgba(240, 147, 251, 0.06) 0%, transparent 50%);
  pointer-events: none;
  z-index: 0;
}

.ledger-page > * { position: relative; z-index: 1; }

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
  position: relative;
  overflow: hidden;
}
.breadcrumb-container::before {
  content: "";
  position: absolute; inset: 0;
  background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.05'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
  opacity: 0.3;
  pointer-events: none;
}
.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255,255,255,0.9);
  font-weight: 500; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;
}
.breadcrumb-item.active :deep(.el-breadcrumb__inner) { color: #fff; font-weight: 600; }
.breadcrumb-icon { font-size: 16px; margin-right: 4px; }

.filter-card, .table-card {
  margin-bottom: 16px;
  background: rgba(255,255,255,0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0,0,0,0.08);
}
.filter-form { display: flex; align-items: center; gap: 12px; }
.filter-actions { display: flex; gap: 12px; }
.toolbar { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.ledger-table { width: 100%; }

.mb-12 { margin-bottom: 12px; }
.mt-12 { margin-top: 12px; }
.w-220 { width: 220px; }
.w-180 { width: 180px; }
.w-100 { width: 100%; }
.flex-row { display: flex; align-items: center; gap: 8px; }
.flex-end { display: flex; justify-content: flex-end; }
</style>
